import {action, observable, computed, runInAction} from 'mobx'
import {FormFieldStore} from "../Form";
import cloneDeep from "lodash/cloneDeep";
import {Animate} from '@/lib/Animate'

export class SelectStore extends FormFieldStore {

    constructor(props) {
        super(props)
        const {options, textField, valueField} = props
        this.textField = textField || this.textField
        this.valueField = valueField || this.valueField
        this.options = cloneDeep(options || [])
        this.animate = new Animate('slide-up') //fade-scaleY
    }

    textField = 'label'
    valueField = 'value'
    @observable options = []
    @observable loading = false
    @observable filteredOptions = []
    @observable filtered = false
    @observable selectedText = ''
    @observable selectedIndex = -1
    @observable isExpanded = false
    @observable isOverPage = false

    @computed get currentOptions() {
        return this.filtered ? this.filteredOptions : this.options
    }

    @computed get classNames() {
        return this.animate.classNames
    }

    @action expand(overPage) {
        this.isExpanded = true
        this.isOverPage = overPage
        this.animate.enter()
    }

    @action collaspe() {
        this.animate.leaveAsync().then(() => {
            runInAction(() => {
                this.isExpanded = false
            })
        })
    }

    @action clearFiltered() {
        this.filtered = false
        this.filteredOptions = []
    }

    @action selectNext() {
        if (this.selectedIndex + 1 < this.currentOptions.length) {
            this.selectedIndex++
        }
    }

    @action selectPrev() {
        if (this.selectedIndex > 0) {
            this.selectedIndex--
        }
    }

    @action changeOverPage(overPage) {
        this.isOverPage = overPage
    }

    @action setModel(value) {
        this.value = value
        const option = this.options.find(t => t[this.valueField] === value)
        if (option) {
            this.selectedText = option[this.textField]
        }
        this.validate()
    }

    @action changeSelectdText(selectedText) {
        this.selectedText = selectedText
    }

    @action changeSelected(text, value, index) {
        this.selectedIndex = index
        this.selectedText = text
        this.value = value
    }

    @action changeFilteredOptions(filteredOptions) {
        this.filtered = true
        this.filteredOptions = filteredOptions
        this.selectedIndex = -1
    }

    @action changeOptions(options) {
        this.options = options
        this.selectedText = ''
        this.selectedIndex = -1
    }


}
